package com.hello;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ianywhere.ultralitejni12.Connection;
import com.ianywhere.ultralitejni12.PreparedStatement;
import com.ianywhere.ultralitejni12.ResultSet;
import com.ianywhere.ultralitejni12.ULjException;

public class HelloActivity extends Activity {
	
	private static final String TAG = "DB";
	AndroidDB db = null;
	private Connection conn; 
	
    private EditText mHost;
    private EditText mPort;
    private Button accbutton;
	
    /** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		  
		//stworzenie bazy 
		db = new AndroidDB(getApplicationContext());
		try {
			conn = db.initialize();
		} catch (ULjException e){
			displayException("Initialization error", e);
		}	    
	}
	
	//sformatowane wyswietlenie wyjatku
	private void displayException(String msg, ULjException e) {
        Toast t = Toast.makeText( getApplicationContext(), msg + "\n" + e.getMessage(), Toast.LENGTH_LONG );
        t.show();
        Log.e( TAG, msg );
        Log.e( TAG, e.toString() );
		 
	}
	
	//synchronizacja 
	public void onSyncClick(View button){
		System.out.println("SYNC\n");
		try{
			db.synchronize();			
		} catch (ULjException e){
			displayException("error sync", e);
		}
		
	}
	
	//za pierwszym razem uzytkownik ma podac port i hosta
    @Override
    protected void onResume() {
        super.onResume();
        if( !isMetaDataStored() ) {
            showDialog(1);
        }
    }
	
    //dialog do spisania host port
    @Override
    protected Dialog onCreateDialog(int id) {
		Dialog dialog = new Dialog(this);
		dialog.setContentView(R.layout.metadatadialog);
        dialog.setTitle("MetaData");
        mHost = (EditText) dialog.findViewById(R.id.editText1);
        mPort = (EditText) dialog.findViewById(R.id.editText2);
        accbutton = (Button) dialog.findViewById(R.id.button1);
        accbutton.setOnClickListener(
        	new View.OnClickListener() {
				
				public void onClick(View v) {
					onOkClick(accbutton);
					
				}
        });
        return dialog;    	
    }
    
    //po kliku ok w dialogu ustaiwiania portu
    public void onOkClick(View button){
		System.out.println("HELL)");
    	String host1 = mHost.getText().toString();
    	int port1 = Integer.parseInt(mPort.getText().toString());
		System.out.println("HELL)");
    	
    	try {
			db.insertHostPort(host1, port1);
		} catch (ULjException e) {
			e.printStackTrace();
		}
    	dismissDialog(1);
    }
    
	private boolean isMetaDataStored() {
		String exist = null;
		try {
			exist = db.executeSingleValueQuery(db.checkstatement);
		} catch (ULjException e){
			// ...
		}
		if (exist == null){
			return false;			
		}
		return true;
	}

	//Wykonanie zapytania i wyswietlenie wynikow
	public void onConnectClick(View button){
		EditText et = (EditText)findViewById(R.id.editText1);
		String query = et.getText().toString();
		ResultSet rs = null;
		try {
			PreparedStatement ps = conn.prepareStatement(query);
			query = query.toLowerCase();
			if (query.startsWith("select")){
				rs = ps.executeQuery();
			} else {
				ps.execute();
				ps.close();			
			}
	    	conn.commit();
	    	
	    	TextView tv = (TextView) findViewById(R.id.editText2);
	    	tv.setText(String.valueOf(""));
	    	if (query.startsWith("select")){
				String res = "empty";
				while(rs.next()){
	    		//Dla wypiasnia kazdej tabeli nalezy dostarczyc metode potrafiaca ja wypisac
					if (query.indexOf("customers") > 0){
						res = showCustomers(rs);
					} else if (query.indexOf("products") > 0){
						res = showProducts(rs);
					} else if (query.indexOf("metadata") > 0){
						res = showMetaData(rs);
					}
					tv.append(res);
				}
	    	}
		} catch (ULjException e) {
			e.printStackTrace();
		}
		
	}

	private String showMetaData(ResultSet rs) throws ULjException {
		String s1 = String.valueOf(rs.getInt(1));
		String s2 = String.valueOf(rs.getString(2));
		String s3 = String.valueOf(rs.getInt(3));
		return String.format("%-4s|%-15s|%-15s|%n", s1,s2,s3);
	}

	private String showProducts(ResultSet rs) throws ULjException {
		String s1 = String.valueOf(rs.getInt(1));
		String s2 = String.valueOf(rs.getString(2));
		String s3 = String.valueOf(rs.getString(3));
		String s4 = String.valueOf(rs.getString(4));
		String s5 = String.valueOf(rs.getString(5));
		
		return String.format("%-4s|%-15s|%-15s|%-15s|%-15s%n", s1,s2,s3,s4,s5);
	}

	private String showCustomers(ResultSet rs) throws ULjException {
		String s1 = String.valueOf(rs.getInt(1));
		String s2 = String.valueOf(rs.getString(2));
		String s3 = String.valueOf(rs.getString(3));
		String s4 = String.valueOf(rs.getString(4));
		String s5 = String.valueOf(rs.getString(5));
		
		return String.format("%-4s|%-15s|%-15s|%-25s|%-15s%n", s1,s2,s3,s4,s5);
		
	}
}
